<template>
  <div>
    <el-dialog :title="title" :visible="visible" @close="close">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="formData.code" />
        </el-form-item>
        <el-form-item label="权限描述">
          <el-input v-model="formData.description" />
        </el-form-item>
        <el-form-item label="权限启用">
          <el-switch
            v-model="formData.enVisible"
            active-value="1"
            inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align: right;">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { addPermission, getPermissionDetail, updatePermission } from '@/api'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ''
    },
    pid: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      formData: {
        name: '', // 权限名称
        code: '', // 权限标识
        description: '', // 权限描述
        enVisible: '0', // 权限启用标识
        type: '', // 类型 区分当前是添加菜单权限点还是按钮权限点
        pid: '' // 添加到哪个节点下，权限点的父id
      },
      formRules: {
        name: [
          { required: true, message: '请填写权限名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请填写权限标识', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.formData.id ? '编辑权限点' : '新增权限点'
    }
  },
  methods: {
    close() {
      this.$emit('close')
      this.$refs.formRef.resetFields()
      this.formData = {
        name: '',
        code: '',
        description: '',
        enVisible: '0',
        type: '',
        pid: ''
      }
    },
    submit() {
      this.$refs.formRef.validate(async(valid) => {
        if (!valid) return
        if (this.formData.id) {
          // 编辑
          await updatePermission(this.formData)
        } else {
          await addPermission({ ...this.formData, type: this.type, pid: this.pid })
        }
        this.$message.success(this.title + '成功')
        this.close()
        this.$emit('update')
      })
    },
    async getDetail(id) {
      const { data } = await getPermissionDetail(id)
      this.formData = data
    }
  }
}
</script>

<style>

</style>
